<template>
  <div class="tag-editor-overlay" @click="handleOverlayClick">
    <div class="tag-editor" @click.stop>
      <div class="editor-header">
        <h3>管理标签</h3>
        <button @click="$emit('close')" class="close-btn">×</button>
      </div>

      <div class="editor-content">
        <!-- 添加新标签 -->
        <div class="add-tag-section">
          <div class="input-group">
            <input
              v-model="newTagName"
              @keyup.enter="addTag"
              placeholder="输入标签名称"
              class="tag-input"
              maxlength="20"
            />
            <div class="color-picker">
              <div
                v-for="color in predefinedColors"
                :key="color"
                class="color-option"
                :class="{ active: newTagColor === color }"
                :style="{ backgroundColor: color }"
                @click="newTagColor = color"
              ></div>
            </div>
            <button @click="addTag" :disabled="!canAddTag" class="add-btn">
              添加
            </button>
          </div>
        </div>

        <!-- 现有标签列表 -->
        <div class="existing-tags">
          <h4>现有标签</h4>
          <div class="tags-list">
            <div
              v-for="tag in availableTags"
              :key="tag.id"
              class="tag-item"
              :class="{ selected: isTagSelected(tag.id) }"
            >
              <span class="tag-preview" :style="{ backgroundColor: tag.color }">
                {{ tag.name }}
              </span>
              <div class="tag-actions">
                <button
                  @click="toggleTag(tag)"
                  class="toggle-btn"
                  :title="isTagSelected(tag.id) ? '移除标签' : '添加标签'"
                >
                  <i :class="isTagSelected(tag.id) ? 'icon-remove' : 'icon-add'"></i>
                </button>
                <button
                  @click="deleteTag(tag.id)"
                  class="delete-btn"
                  title="删除标签"
                >
                  <i class="icon-delete"></i>
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 当前客户的标签 -->
        <div v-if="selectedTags.length > 0" class="selected-tags">
          <h4>当前标签</h4>
          <div class="tags-container">
            <span
              v-for="tag in selectedTags"
              :key="tag.id"
              class="selected-tag"
              :style="{ backgroundColor: tag.color }"
            >
              {{ tag.name }}
              <button @click="removeTag(tag.id)" class="tag-remove">×</button>
            </span>
          </div>
        </div>
      </div>

      <div class="editor-footer">
        <button @click="$emit('close')" class="cancel-btn">取消</button>
        <button @click="saveTags" class="save-btn">保存</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import type { Tag } from '@/types'
import { generateId } from '@/utils'

interface Props {
  clientTags: Tag[]
  availableTags: Tag[]
}

const props = defineProps<Props>()

const emit = defineEmits<{
  close: []
  save: [tags: Tag[]]
  createTag: [tag: Omit<Tag, 'id'>]
  deleteTag: [tagId: string]
}>()

const newTagName = ref('')
const newTagColor = ref('#3B82F6')
const selectedTags = ref<Tag[]>([...props.clientTags])

const predefinedColors = [
  '#3B82F6', // 蓝色
  '#10B981', // 绿色
  '#F59E0B', // 黄色
  '#EF4444', // 红色
  '#8B5CF6', // 紫色
  '#F97316', // 橙色
  '#06B6D4', // 青色
  '#84CC16', // 青绿色
  '#EC4899', // 粉色
  '#6B7280'  // 灰色
]

const canAddTag = computed(() => {
  return newTagName.value.trim().length > 0 && 
         !props.availableTags.some(tag => 
           tag.name.toLowerCase() === newTagName.value.trim().toLowerCase()
         )
})

const isTagSelected = (tagId: string): boolean => {
  return selectedTags.value.some(tag => tag.id === tagId)
}

const addTag = () => {
  if (!canAddTag.value) return

  const newTag: Omit<Tag, 'id'> = {
    name: newTagName.value.trim(),
    color: newTagColor.value
  }

  emit('createTag', newTag)
  
  // 添加到选中标签
  const tagWithId: Tag = {
    ...newTag,
    id: generateId()
  }
  selectedTags.value.push(tagWithId)

  // 重置输入
  newTagName.value = ''
  newTagColor.value = predefinedColors[0]
}

const toggleTag = (tag: Tag) => {
  const index = selectedTags.value.findIndex(t => t.id === tag.id)
  if (index >= 0) {
    selectedTags.value.splice(index, 1)
  } else {
    selectedTags.value.push(tag)
  }
}

const removeTag = (tagId: string) => {
  selectedTags.value = selectedTags.value.filter(tag => tag.id !== tagId)
}

const deleteTag = (tagId: string) => {
  if (confirm('确定要删除这个标签吗？这将从所有客户中移除此标签。')) {
    emit('deleteTag', tagId)
    removeTag(tagId)
  }
}

const saveTags = () => {
  emit('save', selectedTags.value)
}

const handleOverlayClick = () => {
  emit('close')
}

onMounted(() => {
  // 设置默认颜色为第一个预定义颜色
  newTagColor.value = predefinedColors[0]
})
</script>

<style scoped>
.tag-editor-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.tag-editor {
  background: var(--color-surface);
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
}

.editor-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  border-bottom: 1px solid var(--color-border);
}

.editor-header h3 {
  margin: 0;
  font-size: 18px;
  color: var(--color-text);
}

.close-btn {
  width: 28px;
  height: 28px;
  border: none;
  background: transparent;
  color: var(--color-text-secondary);
  cursor: pointer;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  transition: all 0.2s;
}

.close-btn:hover {
  background: var(--color-hover);
  color: var(--color-text);
}

.editor-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.add-tag-section {
  margin-bottom: 24px;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.tag-input {
  padding: 8px 12px;
  border: 1px solid var(--color-border);
  border-radius: 4px;
  font-size: 14px;
  color: var(--color-text);
  background: var(--color-background);
}

.tag-input:focus {
  outline: none;
  border-color: var(--color-primary);
}

.color-picker {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.color-option {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.2s;
}

.color-option:hover {
  transform: scale(1.1);
}

.color-option.active {
  border-color: var(--color-text);
  transform: scale(1.1);
}

.add-btn {
  align-self: flex-start;
  padding: 8px 16px;
  background: var(--color-primary);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.add-btn:hover:not(:disabled) {
  background: var(--color-primary-dark);
}

.add-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.existing-tags,
.selected-tags {
  margin-bottom: 24px;
}

.existing-tags h4,
.selected-tags h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: var(--color-text);
}

.tags-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.tag-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  border: 1px solid var(--color-border);
  border-radius: 6px;
  transition: all 0.2s;
}

.tag-item:hover {
  background: var(--color-hover);
}

.tag-item.selected {
  border-color: var(--color-primary);
  background: rgba(var(--color-primary-rgb), 0.1);
}

.tag-preview {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  color: white;
  font-weight: 500;
}

.tag-actions {
  display: flex;
  gap: 4px;
}

.toggle-btn,
.delete-btn {
  width: 24px;
  height: 24px;
  border: none;
  background: transparent;
  color: var(--color-text-secondary);
  cursor: pointer;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.toggle-btn:hover {
  background: var(--color-primary);
  color: white;
}

.delete-btn:hover {
  background: var(--color-error);
  color: white;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.selected-tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  color: white;
  font-weight: 500;
}

.tag-remove {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  font-size: 14px;
  line-height: 1;
  padding: 0;
  margin-left: 2px;
}

.editor-footer {
  display: flex;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid var(--color-border);
  justify-content: flex-end;
}

.cancel-btn,
.save-btn {
  padding: 8px 24px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.cancel-btn {
  background: var(--color-border);
  color: var(--color-text);
}

.cancel-btn:hover {
  background: var(--color-hover);
}

.save-btn {
  background: var(--color-primary);
  color: white;
}

.save-btn:hover {
  background: var(--color-primary-dark);
}

/* 图标样式 */
.icon-add::before { content: '+'; }
.icon-remove::before { content: '−'; }
.icon-delete::before { content: '🗑'; }

/* 滚动条样式 */
.editor-content::-webkit-scrollbar {
  width: 6px;
}

.editor-content::-webkit-scrollbar-track {
  background: transparent;
}

.editor-content::-webkit-scrollbar-thumb {
  background: var(--color-border);
  border-radius: 3px;
}
</style>